package io.github.talelin.latticy.common.configuration;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * @program: SpringBoot2-project
 * @description: freeMarker模板引擎
 * @author: mrxiao
 * @create: 2022-08-11 09:53
 */
@Configuration
@Slf4j
public class FreeMarkerConfig {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    public String getContent(String templateName, Map<String, Object> params) {
        log.info("使用了{}模板", templateName);
        Template template = null;
        StringWriter stringWriter = new StringWriter();
        try {
            template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
            template.process(params, stringWriter);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        return stringWriter.toString();
    }

}
